package com.hunantv.mglive.ui.handle;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;

import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.utils.HttpUtils;
import com.hunantv.mglive.utils.L;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;

import org.json.JSONException;

import java.util.Map;

/**
 * Created by admin on 2015/12/12.
 */
public class WBHandle implements WeiboAuthListener, IWeiboHandler.Response, HttpUtils.callBack {
    private static final String TAG = "WBHandle";
    public static final String PLATFORM_TYPE_SDK_WB = "4";
    public static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";
    public static final String SCOPE = "all";

    private static WBHandle WBHANDLE;
    private Context mContext;

    private AuthInfo mWeiboAuth;
    private SsoHandler mSsoHandler;
    private HttpUtils http;

    private IWeiboShareAPI mWeiboShareApi;

    private WBHandle(Context context) {
        mContext = context;
        mWeiboAuth = new AuthInfo(context, Constant.WB_APP_ID, REDIRECT_URL, SCOPE);
        mWeiboShareApi = WeiboShareSDK.createWeiboAPI(context, Constant.WB_APP_ID);
        mWeiboShareApi.registerApp();
    }

    public static WBHandle getWBHandle(Context context) {
        if (WBHANDLE == null) {
            WBHANDLE = new WBHandle(context);
        }
        WBHANDLE.mContext = context;
        return WBHANDLE;
    }

    public IWeiboShareAPI getWeiboShareApi() {
        return mWeiboShareApi;
    }

    public void login() {
        mSsoHandler = new SsoHandler((Activity) mContext, mWeiboAuth);
        mSsoHandler.authorize(this);
    }

    public void shareToSinaWB(String title, String des, String linkurl, Bitmap image) {
        WeiboMultiMessage weiboMultiMessage = new WeiboMultiMessage();
        weiboMultiMessage.mediaObject = getWebpageObj(title, des, linkurl, image);
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        request.multiMessage = weiboMultiMessage;
        request.packageName = mContext.getPackageName();
        request.transaction = "wbshare" + String.valueOf(System.currentTimeMillis());

        mWeiboShareApi.sendRequest((Activity) mContext, request, mWeiboAuth, "", new WeiboAuthListener() {

            @Override
            public void onWeiboException(WeiboException arg0) {
            }

            @Override
            public void onComplete(Bundle bundle) {
                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    /**
     * 创建多媒体（网页）消息对象。
     *
     * @return 多媒体（网页）消息对象。
     */
    private WebpageObject getWebpageObj(String title, String des, String linkurl, Bitmap image) {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = title;
        mediaObject.description = des;

//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo);
//        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        if (image != null) {
            mediaObject.setThumbImage(image);
            image.recycle();
        }
        mediaObject.actionUrl = linkurl;
        mediaObject.defaultText = des;
        return mediaObject;
    }


    private TextObject getTextObj(String text) {
        TextObject textObject = new TextObject();
        textObject.text = text;
        return textObject;
    }


    public void authorizeCallBack(int requestCode, int resultCode, Intent data) {
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    public void onComplete(Bundle bundle) {
        String token = getString(bundle, "access_token", "");
        String uid = getString(bundle, "uid", "");
        String expiresIn = getString(bundle, "expires_in", "");

        L.d(TAG + " access_token", token);
        L.d(TAG + " uid", uid);
        L.d(TAG + " expires_in", expiresIn);
        if (!TextUtils.isEmpty(token)) {
            Map<String, String> body = new FormEncodingBuilderEx()
                    .add("accessToken", token)
                    .add("openId", uid)
                    .add("expireTime", expiresIn)
                    .add("platform", PLATFORM_TYPE_SDK_WB)
                    .build();
//            http.post(BuildConfig.URL_THIRD_LOGIN_TOKEN, body);
        } else {
            // 当您注册的应用程序签名不正确时，就会收到错误Code，请确保签名正确
            String code = bundle.getString("code", "");
            L.d(TAG, code);
        }
    }

    private String getString(Bundle bundle, String key, String defaultValue) {
        if (bundle != null) {
            String value = bundle.getString(key);
            return value != null ? value : defaultValue;
        } else {
            return defaultValue;
        }
    }

    @Override
    public void onWeiboException(WeiboException e) {
        e.printStackTrace();
        L.e("weibo", e);
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                break;
        }
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException {
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
    }

    @Override
    public void onCancel() {

    }

    @Override
    public boolean get(String url, Map<String, String> param) {
        return http.get(url, param);
    }

    @Override
    public boolean post(String url, Map<String, String> param) {
        return http.post(url, param);
    }

    @Override
    public void onError(String url, Exception e) {

    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        return null;
    }


}
